﻿using Frame;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace VideoFileOrganization.BatchRename
{
    public partial class BatchRenameFrm : BaseFrm
    {

        public delegate void ExecuteButtonEventHanle(int index);
        public event ExecuteButtonEventHanle ExecuteButtonEvent;


        
        public BatchRenameFrm()
        {
            InitializeComponent();
            this.Text = "批量重命名";
            this.TabImage = Properties.Resources.BatchRename;
            this.Index = 2;
            rbtnFolder.Checked = true;
            dgView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            
        }

        protected override void IniUi()
        {
            
            dgView.Rows.Clear();
            string[] subfolders;
            if (rbtnFolder.Checked)
            {
                subfolders = Directory.GetDirectories(RootPath);
            }
            else
            {
                subfolders = Directory.GetFiles(RootPath).Where(file => !File.GetAttributes(file).HasFlag(FileAttributes.Hidden))
    .ToArray();//获取当前目录下的子文件 不要隐藏文件              
            }
            for (int row = 0; row < subfolders.Count(); row++)
            {
                dgView.Rows.Add();
                dgView.Rows[row].Cells[0].Value = subfolders[row];
                dgView.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
            


        }


        private void MoveFolder(string[] sources, string[] targets)
        {
            for (int i = 0; i < targets.Count(); i++)
            {
                if (sources[i] == targets[i]) continue;
                if (Directory.Exists(targets[i]))
                {
                    // 目标文件夹已存在，只移动源文件夹中的子文件
                    MoveSubFiles(sources[i], targets[i]);
                    Directory.Delete(sources[i], true); // 删除源文件夹
                }
                else
                {
                    Directory.Move(sources[i], targets[i]);
                }
            }            
        }

        private void MoveSubFiles(string sourceFolder, string destinationFolder)
        {
            string[] files = Directory.GetFiles(sourceFolder);

            foreach (string file in files)
            {
                string destinationFile = Path.Combine(destinationFolder, Path.GetFileName(file));
                File.Move(file, destinationFile);
            }

            string[] subFolders = Directory.GetDirectories(sourceFolder);

            foreach (string subFolder in subFolders)
            {
                string destinationSubFolder = Path.Combine(destinationFolder, Path.GetFileName(subFolder));
                MoveFolder(new[] { subFolder }, new[] { destinationSubFolder });
            }
        }

        private void Rename()
        {
            string[] sorces = new string[dgView.Rows.Count];
            for (int i = 0; i < dgView.Rows.Count; i++)
            {
                sorces[i] = dgView.Rows[i].Cells[0].Value.ToString();
            }
            string[] targets = new string[dgView.Rows.Count];
            for (int i = 0; i < dgView.Rows.Count; i++)
            {
                targets[i] = dgView.Rows[i].Cells[1].Value.ToString();

            }
            MoveFolder(sorces, targets);
        }
        private delegate void RenameDelegate();
        private void RenameThread(object obj)
        {
            Invoke(new RenameDelegate(Rename));
            SendMsg("重命名完成", LogLevel.INFO);
                
        }

        protected override void ApplyButton()
        {
            Thread thread = new Thread(new ParameterizedThreadStart(RenameThread));
            thread.IsBackground = true;
            thread.Start();
        }



        private void btnExecute_Click(object sender, EventArgs e)
        {
            ExecuteButtonEvent(tabRenameFrm.SelectedIndex);           
        }

        private void BatchRenameFrm_Load(object sender, EventArgs e)
        {
            tabRenameFrm.TabPages.Clear();
            imageList1.Images.Clear();
            foreach (RenameBaseFrm frm in global.renameSubFormDic.Values)
            {
                AddFrm(frm);            
            }  
                    
        }

        private void AddFrm(RenameBaseFrm frm)
        {
            frm.TopLevel = false;
            frm.FormBorderStyle = FormBorderStyle.None;
            frm.Dock = DockStyle.Fill;
            frm.sendMessageEvent += new RenameBaseFrm.SenMessageEventHanle(SendToLogWindows);
            this.ExecuteButtonEvent += new ExecuteButtonEventHanle(frm.OnApplyButton);
            frm.ReviseEvnet += new RenameBaseFrm.ReviseHandlde(Revise);            
            frm.global = global;
            tabRenameFrm.TabPages.Add(frm.Text);
            frm.Parent = tabRenameFrm.TabPages[tabRenameFrm.TabPages.Count - 1];
            imageList1.Images.Add(frm.TabImage);
            tabRenameFrm.ImageList = imageList1;
            int index = imageList1.Images.Count - 1;
            tabRenameFrm.TabPages[index].ImageIndex = index;         
            frm.Show();
            frm.UpdataUi(index);
        }

        private void SendToLogWindows(string Msg, LogLevel l)
        {
            SendMsg(Msg, l);
        }


        private void Revise(BatchRenameClass.tReviseParam param)
        {

            Thread thread = new Thread(new ParameterizedThreadStart(ReviseThread));
            thread.IsBackground = true;
            thread.Start(param);
            //thread.Join();
            //myDataGridView1.AutoResizeColumns(); // 自动调整所有列的宽度
        }

        private void ReviseThread(object obj)
        {
            BatchRenameClass.tReviseParam param = (BatchRenameClass.tReviseParam)obj;
            int rows = DelegateControl.GetDataGridViewRowsCount(dgView);
            string[] sorces = new string[rows];
            for (int i = 0; i < rows; i++)
            {
                sorces[i] = DelegateControl.GetDataGridViewValue(dgView, i, 0);
            }
            string[] targets = new string[rows];
            switch (param.mode)
            {
                case BatchRenameClass.eReviseMode.BEFORE_A_RESERVED_CHARACTER:
                case BatchRenameClass.eReviseMode.AFTER_A_RESERVED_CHARACTER:
                    targets = global.BatchRename.character_interception(sorces, param);
                    break;
                case BatchRenameClass.eReviseMode.RETAIN_CHINESE:
                case BatchRenameClass.eReviseMode.RETAIN_ENGLISH:
                case BatchRenameClass.eReviseMode.RETAIN_NUMBER:
                    targets = global.BatchRename.character_reservation(sorces, param);
                    break;
                case BatchRenameClass.eReviseMode.REPLACE_THE_CHARACTERS:
                    targets = global.BatchRename.RespaceName(sorces, param);
                    break;
            }
            for (int i = 0; i < rows; i++)
            {
                DelegateControl.SetDataGridViewValue(dgView, i, 1, targets[i]);
            }
            DelegateControl.ResizeColumns(dgView);
            global.SaveHistory();
        }

        private void tabRenameFrm_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }
    }
}
